package tchk.xyz.lingyuntutorminiprogram.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tchk.xyz.lingyuntutorminiprogram.entity.TeacherSchedule;
import tchk.xyz.lingyuntutorminiprogram.mapper.TeacherScheduleMapper;
import tchk.xyz.lingyuntutorminiprogram.service.ITeacherScheduleService;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

@Service
public class TeacherScheduleServiceImpl extends ServiceImpl<TeacherScheduleMapper, TeacherSchedule> implements ITeacherScheduleService {

    @Override
    @Transactional
    public void updateTeacherSchedule(Long userId, List<TeacherSchedule> schedules) {
        // 1. 先删除该用户所有 'available' 状态的日程
        this.remove(new LambdaQueryWrapper<TeacherSchedule>()
                .eq(TeacherSchedule::getUserId, userId)
                .eq(TeacherSchedule::getStatus, "available"));

        // 2. 批量插入新的日程
        if (schedules != null && !schedules.isEmpty()) {
            for (TeacherSchedule schedule : schedules) {
                // [核心修正] 增加健壮性判断
                if (schedule.getScheduleDate() == null || schedule.getStartTime() == null) {
                    continue; // 如果日期或时间为空，则跳过这条脏数据
                }
                schedule.setUserId(userId);
                schedule.setStatus("available");
                // [核心修正] 如果endTime为空，则默认设置为 startTime + 59分钟
                if (schedule.getEndTime() == null) {
                    schedule.setEndTime(schedule.getStartTime().plusMinutes(59));
                }
            }
            this.saveBatch(schedules);
        }
    }

    @Override
    public List<TeacherSchedule> getScheduleForWeek(Long userId, String dateStr) {
        LocalDate date;
        try {
            // [核心修正] 增加 try-catch，对前端传来的参数进行校验
            date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE);
        } catch (DateTimeParseException e) {
            // 如果前端传来 "NaN-NaN-NaN" 或其他非法格式，则使用当前服务器日期作为默认值
            // 这样可以保证后端永远不会崩溃
            date = LocalDate.now();
        }

        LocalDate monday = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate sunday = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

        return this.list(new LambdaQueryWrapper<TeacherSchedule>()
                .eq(TeacherSchedule::getUserId, userId)
                .ge(TeacherSchedule::getScheduleDate, monday)
                .le(TeacherSchedule::getScheduleDate, sunday));
    }
}